package com.frost.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class zkClient {

    // 注意：逗号后面不能有空格
    private String connectString = "centos102:2181,centos103:2181,centos104:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;

    // 创建客户端
    @Before
    public void init() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {

                List<String> children = null;
                try {
                    System.out.println("==============================");
                    children = zkClient.getChildren("/", true);

                    for (String child : children) {
                        System.out.println(child);
                    }
                    System.out.println("==============================");

                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }
        });
    }

    // 创建节点
    @Test
    public void create() throws InterruptedException, KeeperException {
        String nodeCreated = zkClient.create("/frost", "cat".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    }

    // 查找所有节点
    @Test
    public void getChildren() throws InterruptedException, KeeperException {
//        List<String> children = zkClient.getChildren("/", true);

//        for (String child : children) {
//            System.out.println(child);
//        }

        // 延时
        Thread.sleep(Long.MAX_VALUE);
    }

    // 判断节点是否存在
    @Test
    public void exit() throws InterruptedException, KeeperException {
        Stat stat = zkClient.exists("/frost", false);
        System.out.println(stat == null ? "not exits" : "exits");
    }

}
